import React from 'react';
import { observer, inject } from 'mobx-react';
import { WeaErrorPage,WeaTools, WeaLocaleProvider,WeaRichText } from 'ecCom';
import {Button} from 'antd';
import {WeaTableNew} from 'comsMobx';
const WeaTable = WeaTableNew.WeaTable;
import * as _ from '../../util/common';
import '../../style/formResource.less';
import isEqual from 'lodash/isEqual';
import isFunction from 'lodash/isFunction';
const getLabel = WeaLocaleProvider.getLabel;

@observer
class CommunicationRichText extends React.Component {
    constructor(props) {
        super(props);
        this.initValue = {
          richValue: '',
          anonymous: 0,
          relatedaccList4E9: [],
          relatedcusList4E9: [],
          relateddocList4E9: [],
          relatedprjList4E9: [],
          relatedwfList4E9: [],
          relatemutilprjs4E9: []
        };
        this.state = {
          disableSubmit: false,
          ...this.initValue,
          richValue: props.richValue,
          anonymous: props.anonymous,
          placeholder: props.placeholder || '', 
          relatedaccList4E9: props.relatedaccList4E9 || [],
          relatedcusList4E9: props.relatedcusList4E9 || [],
          relateddocList4E9: props.relateddocList4E9 || [],
          relatedprjList4E9: props.relatedprjList4E9 || [],
          relatedwfList4E9: props.relatedwfList4E9 || [],
          relatemutilprjs4E9: props.relatemutilprjs4E9 || []
        };
      }
      componentDidMount() {
        // window.CK_REF['communication_ck'] = this.refs.rich;
      }
      componentWillReceiveProps(nextProps) {
        let newState = {};
        if (nextProps.richValue != this.props.richValue) {
          newState.richValue = nextProps.richValue;
        }
        if (!isEqual(nextProps.relatedaccList4E9, this.props.relatedaccList4E9)) {
          newState.relatedaccList4E9= nextProps.relatedaccList4E9;
        }
        if (!isEqual(nextProps.relatedcusList4E9, this.props.relatedcusList4E9)) {
          newState.relatedcusList4E9 = nextProps.relatedcusList4E9;
        }
        if (!isEqual(nextProps.relateddocList4E9, this.props.relateddocList4E9)) {
          newState.relateddocList4E9 = nextProps.relateddocList4E9;
        }
        if (!isEqual(nextProps.relatedprjList4E9, this.props.relatedprjList4E9)) {
          newState.relatedprjList4E9 = nextProps.relatedprjList4E9;
        }
        if (!isEqual(nextProps.relatedwfList4E9, this.props.relatedwfList4E9)) {
          newState.relatedwfList4E9 = nextProps.relatedwfList4E9;
        }
        if (!isEqual(nextProps.relatemutilprjs4E9, this.props.relatemutilprjs4E9)) {
          newState.relatemutilprjs4E9 = nextProps.relatemutilprjs4E9;
        }
        if(nextProps.placeholder !== this.props.placeholder) {
          newState.placeholder = nextProps.placeholder;
        }
        this.setState(newState);
      }
      componentUnMount() {
        this.setState({anonymous: 0});
        
      }

      componentDidUpdate() {
        let that  = this;
        this.timer = setTimeout(() => {
          console.log(111)
          clearTimeout(that.timer);
          // this.focus();
        }, 1);
      }
      createBrowserConfig = (type, text, icon, key, isSingle, att) => {
        let replaceDatas = this.state[key] || [];
        return {
          name: att ? att : 'Browser',
          show: (
            <div className="wea-cowork-rich-button">
              <i className={icon}/>
              {replaceDatas.length > 0 && <div className="red-point" />}
              <span className="button-text">{text}</span>
            </div>
          ),
          title: text,
          memorise: true,
          type,isSingle,replaceDatas
        };
      }

      initExtentsConfig() {
        const { requestid = -1 } = this.props;
        let configArr = [];
        configArr.push({
            name: "At",
            position: "last",
            tipTitle: getLabel(124785, "在签字意见框中输入@可直接选择节点参与人"),
            request: {
                url: "/api/workflow/forward/getReqWfNodeOperators?isDistinct=1",
                type: "GET",
                params: {
                    requestid: requestid
                }
            }
        });
        return configArr;
    }
    render(){
        let {richValue,anonymous,disableSubmit, placeholder } = this.state;
        let { noBottomInfo, appStatus, noNeedCancelBtn=false, noNeedSubmitBtn=false} = this.props;
        let bottomBarConfig = [];
        if (!noBottomInfo) {
          if (appStatus.doc == 1) {
            bottomBarConfig.push(this.createBrowserConfig(37, getLabel(126529, '文档'), "icon-coms-content-o", 'relateddocList4E9', false));
          }
          if (appStatus.workflow == 1) {
            bottomBarConfig.push(this.createBrowserConfig(152, getLabel(131692, '流程'), "icon-coms-Workflow-o", 'relatedwfList4E9', false));
          }
          if (appStatus.crm == 1) {
            bottomBarConfig.push(this.createBrowserConfig(18, getLabel(84236, '客户'), "icon-coms-currency-Customer", 'relatedcusList4E9', false));
          }
          if (appStatus.project == 1) {
            bottomBarConfig.push(this.createBrowserConfig(135, getLabel(22245, '项目'), "icon-coms-project", 'relatemutilprjs4E9', false));
          }
          if (appStatus.task == 1) {
            bottomBarConfig.push(this.createBrowserConfig('prjtsk', getLabel(1332, '任务'), "icon-coms-currency-Task", 'relatedprjList4E9', false));
          }
          if (appStatus.attachment == 1) {
            let datas = this.state.relatedaccList4E9 || [];
            datas = datas.map((data) => {
              return {
                fileExtendName: data.docextendname,
                fileid: data.id,
                filelink: data.url,
                filename: data.name,
                filesize: data.downName,
                // imgSrc	string	是	附件图标
                loadlink: data.downUrl,
                // showLoad	bool	否	是否可下载
                // showDelete	bool	否	是否可删除
                // isImg	bool	否	非图片模式下是表示文件是否是图片格式
                ...data
              }
            });
            bottomBarConfig.push({
              name: 'Upload', // 上传组件
              type: 'list', // 上传组件类型
              show: (
                <div className="wea-cowork-rich-button wea-cowork-upload-button">
                  <i className="icon-coms-currency-Enclosure" title={getLabel(128095, ' 上传附件')} />
                  {datas.length > 0 && <div className="red-point" />}
                  <span className="button-text" title={getLabel(385751, '附件上传(最大)')+ appStatus.maxFileSize +getLabel(83528, 'M/个') + ')'}>{getLabel(132024, '附件')}</span>
                </div>
              ), // 使用 antd 图标
                uploadUrl: '/api/cowork/base/uploadOperate?secId='+appStatus.accCatelog, // 上传地址
                maxUploadSize : appStatus.maxFileSize,
                category: appStatus.accCatelog , // 文档目录
                onListChange: (ids, list) => {
                  this.setState({
                    relatedaccList4E9: list
                });
              },
              datas
            });
          }
        }
        let extentsConfig = this.initExtentsConfig(extentsConfig);
        let rightList = [];
        if(!noNeedSubmitBtn) {
          rightList.push(
            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@3gifrd@submit`} className="wea-button-release" onClick={this.submit} style={{marginLeft: "10px", top: "2px"}}>
                <span>
                  <span className="icon-coms-Release" />
                  <span>{getLabel(615, ' 提交')}</span>
                </span>
            </Button>
          );
        }
        if(!noNeedCancelBtn) {
          rightList.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@kpl65m@cancel`} onClick={this.cancel} style={{marginLeft: "10px", top: "2px"}}><span ref='cancel'>{getLabel(201, '取消')}</span></Button>);
        }

        return (
            <div className='wf-resources' >
               <WeaRichText ecId={`${this && this.props && this.props.ecId || ''}_WeaRichText@x8ga6a`}
                    ls={true}
                    value={richValue}
                    
                    ckConfig={{
                    toolbar:[
                        { name: 'document', items: [ 'Source'] },
                        { name: 'paragraph', items: [ 'JustifyLeft', 'JustifyCenter', 'JustifyRight', '-', 'NumberedList', 'BulletedList' ] },
                        { name: 'styles', items: [ 'Format', 'Font', 'FontSize' ] },
                        { name: 'colors', items: [ 'TextColor' ] },
                        { name: 'basicstyles', items: [ 'Bold', 'Italic', 'Underline', 'Strike', ] },
                        { name: 'insert', items: [ 'Image', 'Table', 'Smiley'] },
                        { name: 'tools', items: [ 'Maximize' ] }
                    ],
                    extraPlugins: 'autogrow',
                    height:150,
                    autoGrow_minHeight: 150,
                    autoGrow_maxHeight: 600,
                    removePlugins: 'resize',
                    uploadUrl: '/api/doc/upload/uploadFile',
                    placeholder: placeholder
                    }}
                    ref="rich"
                    className="wea-workflow-rich-text"
                    bottomBarConfig={bottomBarConfig}
                    bootomBarStyle={{}}
                    bottomBarRight={rightList.length > 0 && {Component: rightList}}
                    onStatusChange={s => {
                    if (s == 'ready') {
                        this.focus();
                    }
                    }}
                    onToolsChange={this.onToolsChange}
                    extentsConfig={extentsConfig}
                />
            </div>
        )
    }

    createBrowserConfig = (type, text, icon, key, isSingle, att) => {
        let replaceDatas = this.state[key] || [];
        return {
          name: att ? att : 'Browser',
          show: (
            <div className="wea-cowork-rich-button">
              <i className={icon}/>
              {replaceDatas.length > 0 && <div className="red-point" />}
              <span className="button-text">{text}</span>
            </div>
          ),
          title: text,
          memorise: true,
          type,isSingle,replaceDatas
        };
      }

      onToolsChange = (name = '', ids = '', list = [], type = '') => {
        if (type == 'image') {
          let str = list.reduce((sum, img) => {
            return sum + `<img src="${img.imgSrc}"/>&#8203`
          }, '');
          return str;
        }
        let key = '';
        switch (type) {
          case 37:
            key = 'relateddocList4E9';
            break;
          case 152:
            key = 'relatedwfList4E9';
            break;
          case 18:
            key = 'relatedcusList4E9';
            break;
          case 135:
            key = 'relatemutilprjs4E9';
            break;
          case 'prjtsk':
            key = 'relatedprjList4E9';
            break;
          default:
            break;
        }
        let newState = {};
        newState[key] = list;
        this.setState(newState);
        this.focus();
        return ' ';
      }

      focus = () => {
        let that = this;
        that.timer = setTimeout( () => {
          clearTimeout(that.timer);          
          that.refs.rich && that.refs.rich.focus('last');
        },100)
      }

      getSubmitParams = () => {
        let {richValue,
          anonymous,
          relatedaccList4E9= [],
          relatedcusList4E9= [],
          relateddocList4E9= [],
          relatedprjList4E9= [],
          relatedwfList4E9= [],
          relatemutilprjs4E9= []} = this.state;
          //获取富文本输入值
        richValue =  this.refs.rich.getData();
        let params = {remark: richValue, isAnonymous: anonymous};
        params.relatedprj = relatedprjList4E9.map((obj) => obj.id).join();
        params.relatedcus = relatedcusList4E9.map((obj) => obj.id).join();
        params.relatedwf = relatedwfList4E9.map((obj) => obj.id).join();
        params.relateddoc = relateddocList4E9.map((obj) => obj.id).join();
        params.projectIDs = relatemutilprjs4E9.map((obj) => obj.id).join();
        params.relatedacc = relatedaccList4E9.map((obj) => obj.fileid || obj.id).join();
        return params;
      }

      submit = () => {
        this.props.submit(this.getSubmitParams(), () => {
          this.setState({richValue: ""})
          this.refs.rich && this.refs.rich.setData(''); //清空富文本输入内容
          this.clear();
          this.props.clearReplyInfo && this.props.clearReplyInfo();
        });
      }

      clear = () => {
        this.setState({
          ...this.initValue
        });
      }

      cancel = () => {
        if (isFunction(this.props.cancel)) {
          this.props.cancel(this.state.richValue);
        }
      }
}

export default WeaTools.tryCatch(React, 
    props => <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@poiwoa`} msg={ props.error ? props.error : getLabel(383324,'对不起，该页面异常，请联系管理员')} />,
    {error: ""}
)(CommunicationRichText);